package com.platform.auth.controller;

import com.platform.common.result.R;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import java.security.KeyPair;
import java.security.Principal;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

@Api(tags = "auth控制台", description = "为了能够捕获在认证过程中出现的所有异常，" +
        "这里通过复写security中的token入口，来实现此目的 内容其实少，就是手动去调用tokenPoint的方法触发。")
@RestController
@RequestMapping("/oauth")
@AllArgsConstructor
@Slf4j
public class AuthController {

    private final TokenEndpoint tokenEndpoint;
    private KeyPair keyPair;

    @ApiOperation("获取token")
    @PostMapping("/token")
    public Object postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        return R.ok(tokenEndpoint.postAccessToken(principal, parameters).getBody());
    }

    @GetMapping("/public-key")
    public Map<String, Object> getPublicKey() {
        RSAKey key = new RSAKey.Builder((RSAPublicKey) keyPair.getPublic()).build();
        return new JWKSet(key).toJSONObject();
    }
}
